﻿using System;
using System.Collections.Generic;
using System.Linq;


using MDT_MonitorModel;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;

// Pour en savoir plus sur le modèle d'élément Page Éléments groupés, consultez la page http://go.microsoft.com/fwlink/?LinkId=234231
//http://localhost:9801/MDTMonitorData/Computers
/*
 * http://localhost:9800/MDTMonitorEvent/PostEvent?uniqueID=12345678-1234-1234-1234-123456789ABC&computerName=computer1&messageID=message&severity=low&stepName=step2&currentStep=2&totalSteps=7&id=1&message=message&dartIP=10.12.034.12&dartPort=123&dartTicket=12343564&vmHost=hyper-V&vmName=myVM
 * 
 * 
 */
namespace MDT_Metro_monitoring
{
    /// <summary>
    /// Page affichant une collection groupée d'éléments.
    /// </summary>
    public sealed partial class ComputersTitles : MDT_Metro_monitoring.Common.LayoutAwarePage
    {

        DispatcherTimer updateTimer;

        public ComputersTitles()
        {
            this.InitializeComponent();
            SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
        }

        void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            args.Request.ApplicationCommands.Clear();
            SettingsCommand cmd = new SettingsCommand("sample", "Servers management", (uiCommand) =>
            {
                openServerManagementSnapIn();
            });

            args.Request.ApplicationCommands.Add(cmd);

            cmd = new SettingsCommand("sample", "About", (uiCommand) =>
            {
                openAboutSnapIn();
            });

            args.Request.ApplicationCommands.Add(cmd);
        }


        private void openAboutSnapIn()
        {
            Popup _settingsPopup = new Popup();
            App.updateAvailable = false;
            _settingsPopup.Closed += OnPopupClosed;
            _settingsPopup.LostFocus += OnFocusLost;
            _settingsPopup.PointerCaptureLost += OnPointerCaptureLost;
            //Window.Current.Activated += OnWindowActivated;
            _settingsPopup.IsLightDismissEnabled = true;
            _settingsPopup.Width = 646;
            _settingsPopup.Height = Window.Current.Bounds.Height;

            AboutSettings mypane = new AboutSettings();
            mypane.Width = 646;
            mypane.Height = Window.Current.Bounds.Height;


            _settingsPopup.Child = mypane;
            _settingsPopup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - 646);
            _settingsPopup.SetValue(Canvas.TopProperty, 0);
            _settingsPopup.IsOpen = true;
        }

        private void openServerManagementSnapIn()
        {
            Popup _settingsPopup = new Popup();
            App.updateAvailable = false;
            _settingsPopup.Closed += OnPopupClosed;
            _settingsPopup.LostFocus += OnFocusLost;
            _settingsPopup.PointerCaptureLost += OnPointerCaptureLost;
            //Window.Current.Activated += OnWindowActivated;
            _settingsPopup.IsLightDismissEnabled = true;
            _settingsPopup.Width = 646;
            _settingsPopup.Height = Window.Current.Bounds.Height;

            ServerManagementSettings mypane = new ServerManagementSettings();
            mypane.Width = 646;
            mypane.Height = Window.Current.Bounds.Height;


            _settingsPopup.Child = mypane;
            _settingsPopup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - 646);
            _settingsPopup.SetValue(Canvas.TopProperty, 0);
            _settingsPopup.IsOpen = true;
        }

        private void OnPointerCaptureLost(object sender, PointerRoutedEventArgs e)
        {
            App.updateAvailable = true;
        }

        private void OnFocusLost(object sender, RoutedEventArgs e)
        {
            App.updateAvailable = true;
        }

        private void OnPopupClosed(object sender, object e)
        {
            App.updateAvailable = true;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            //pageTitle.Text = "Monitor";

            //this.DefaultViewModel["Overview"] = ((DataSources)navigationParameter).ItemGroups;

            LoadServers();
            //LoadComputers();
            updateTimer = new DispatcherTimer();
            updateTimer.Interval = new TimeSpan(0, 0, 10);
            updateTimer.Tick += UpdateUI;
            updateTimer.Start();
        }

        private void UpdateUI(object sender, object e)
        {
            if (App.updateAvailable)
            {
                //LoadComputers();
                LoadServers();
            }
        }

        private async void LoadServers()
        {
            List<IComputer> dictionary = new List<IComputer>();
            //Lock this section cause Servers collection could be modified using the settings panel
            if(App.updateAvailable) {
                if (App.Servers != null)
                {
                    foreach (Server srv in App.Servers)
                    {
                        await srv.testConnectivity();
                        if (srv.Online)
                        {
                            srv.Clients = (List<Computer>)await srv.ClientData.LoadComputersAsync();
                            if (srv.Clients != null)
                                dictionary.AddRange(srv.Clients);
                        }
                    }
                }
            }
            if (App.Servers != null)
            {
                dictionary.AddRange(App.Servers);
            }
            Server fake = new Server("", "");
            fake.isFake = true;
            dictionary.Add(fake);
            
            var resultClient = (from cp in dictionary where cp.Type=="Computers" orderby cp.sort1 descending, cp.sort2 descending, cp.sort3 select cp).Take(12);
            var resultServer = (from cp in dictionary where cp.Type=="Servers" orderby cp.sort1 descending, cp.sort2 descending, cp.sort3 descending select cp).Take(12);

            var result = from cp in (from cpt in resultClient.Union(resultServer) orderby cpt.StatusId select cpt) group cp by cp.Type into grp orderby grp.Key descending select grp;

            //Default view
            if (App.Servers != null)
                this.NbServer.Text = App.Servers.Count.ToString();
            else
                this.NbServer.Text = "0";

            this.NbServerOffline.Text = (from srv in resultServer where srv.Status == "Offline" select srv).Count().ToString();

            this.NbClientError.Text = (from cp in resultClient where (int)cp.sort1 != 0 select cp).Count().ToString();
            this.NbClientWarning.Text = (from cp in resultClient where (int)cp.sort2 != 0 select cp).Count().ToString();

            short sum = 0;
            int count = 0;
            foreach (Computer c in resultClient)
            {
                if(c.PercentComplete != null){
                    sum += (short)c.PercentComplete;
                    count++;
                }
            }
            if(count != 0)
                this.InstallationCompletion.Text = Math.Round((decimal)(sum / count),0).ToString() + "%";
            else
                this.InstallationCompletion.Text = "--";

            //Portrait view
            this.NbServerPortrait.Text = this.NbServer.Text;
            this.NbServerOfflinePortrait.Text = this.NbServerOffline.Text;

            this.NbClientErrorPortrait.Text = this.NbClientError.Text;
            this.NbClientWarningPortrait.Text = this.NbClientWarning.Text;
            this.InstallationCompletionPortrait.Text = this.InstallationCompletion.Text;

            //Snapped view
            this.NbServerSnapped.Text = this.NbServer.Text;
            this.NbServerOfflineSnapped.Text = this.NbServerOffline.Text;

            this.NbClientErrorSnapped.Text = this.NbClientError.Text;
            this.NbClientWarningSnapped.Text = this.NbClientWarning.Text;
            this.InstallationCompletionSnapped.Text = this.InstallationCompletion.Text;

            this.serverSource.Source = result;

        }

        private void ComputerItem_click(object sender, ItemClickEventArgs e)
        {
            var item = (Computer)e.ClickedItem;
            this.Frame.Navigate(typeof(ItemDetailPage), item);
        }

        private void ServerTitle_click(object sender, RoutedEventArgs e)
        { 
            this.Frame.Navigate(typeof(GroupedItems), ((Button)sender).Content);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            LoadServers();
        }

        public void addServer(Server s)
        {
            App.addServer(s);
        }

        public void removeServer(Server s)
        {
            App.removeServer(s);
        }

        private void Item_click(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem.GetType() == typeof(Computer))
            {
                var item = (Computer)e.ClickedItem;
                this.Frame.Navigate(typeof(ItemDetailPage), item);
            }
            else if (e.ClickedItem.GetType() == typeof(Server))
            {
                var item = (Server)e.ClickedItem;
                if(item.isFake)
                    openServerManagementSnapIn();
                else
                    this.Frame.Navigate(typeof(ServerDetailPage), item);
            }
            else
            {
                
            }
        }

        private void ComputerTitle_click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ComputerGroupedItems), null);
        }

        private void Overview_Client(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(GroupedItems), "Computers");
        }

        private void Overview_Server(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(GroupedItems), "Servers");
        }
    }

}
